package com.ruoyi.system.service.impl;

import java.math.BigDecimal;
import java.util.List;

import com.fazecast.jSerialComm.SerialPort;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.WeightConfig;
import com.ruoyi.system.domain.WeightResult;
import com.ruoyi.system.service.IWeightConfigService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.CarsMapper;
import com.ruoyi.system.domain.Cars;
import com.ruoyi.system.service.ICarsService;

/**
 * 车辆Service业务层处理
 * 
 * @author he
 * @date 2025-08-06
 */
@Service
public class CarsServiceImpl implements ICarsService
{
    @Autowired
    private CarsMapper carsMapper;

    @Autowired
    private IWeightConfigService iWeightConfigService;

    /**
     * 查询车辆
     * 
     * @param id 车辆主键
     * @return 车辆
     */
    @Override
    public Cars selectCarsById(Long id)
    {
        return carsMapper.selectCarsById(id);
    }

    /**
     * 查询车辆列表
     * 
     * @param cars 车辆
     * @return 车辆
     */
    @Override
    public List<Cars> selectCarsList(Cars cars)
    {
        return carsMapper.selectCarsList(cars);
    }

    /**
     * 新增车辆
     * 
     * @param cars 车辆
     * @return 结果
     */
    @Override
    public int insertCars(Cars cars)
    {

        return carsMapper.insertCars(cars);
    }

    /**
     * 修改车辆
     * 
     * @param cars 车辆
     * @return 结果
     */
    @Override
    public int updateCars(Cars cars)
    {

        return carsMapper.updateCars(cars);
    }

    /**
     * 批量删除车辆
     * 
     * @param ids 需要删除的车辆主键
     * @return 结果
     */
    @Override
    public int deleteCarsByIds(Long[] ids)
    {
        return carsMapper.deleteCarsByIds(ids);
    }

    /**
     * 删除车辆信息
     * 
     * @param id 车辆主键
     * @return 结果
     */
    @Override
    public int deleteCarsById(Long id)
    {
        return carsMapper.deleteCarsById(id);
    }

    @Override
    public List<Cars> getCarInfoOptions(String paramName) {

        return carsMapper.getCarInfoOptions(paramName);
    }

    @Override
    public int updateApprovalState(List<Long> idsToUpdate, Integer code) {
        return carsMapper.updateApprovalState(idsToUpdate,code);
    }

    @Override
    public String getWeight() {

        //初始化删除表数据
        carsMapper.deleteWeight();
        //获取 地磅配置信息 串口 数据位
        List<WeightConfig> weightConfigs = iWeightConfigService.selectWeightConfigList(new WeightConfig());
        if (CollectionUtils.isNotEmpty(weightConfigs)) {
            WeightConfig weightConfig = weightConfigs.get(0);

            SerialPort ports = SerialPort.getCommPort(weightConfig.getCommPorts());

            if (ObjectUtils.isNotEmpty(ports)) {

                SerialPort comPort = ports;
                comPort.setBaudRate(weightConfig.getBaudRate()); // 设置波特率
                comPort.setNumDataBits(weightConfig.getDataBits()); // 设置数据位
                comPort.setNumStopBits(weightConfig.getStopBits()); // 设置停止位
                comPort.setParity(weightConfig.getParity()); // 设置校验位为无校验
                try {
                    comPort.openPort(); // 打开串口
                    System.out.println("Port opened: " + comPort.getDescriptivePortName());
                    // 等待一段时间让数据到达
                    Thread.sleep(500);

                    for (int i = 0; i < 3; i++) {
                        Thread.sleep(1000);
                        // 检查可用的字节数
                        int availableBytes = comPort.bytesAvailable();
                        if (availableBytes > 0) {
                            byte[] readBuffer = new byte[availableBytes]; // 创建读取缓冲区
                            int numRead = comPort.readBytes(readBuffer, readBuffer.length); // 读取数据到缓冲区
                            if (numRead > 0) {
                                System.out.println("Read " + numRead + " bytes."); // 打印读取的字节数
                                String receivedData = new String(readBuffer, 0, numRead); // 将字节转换为字符串
                                System.out.println("Data received: " + receivedData); // 打印接收到的数据

                                //处理字符串 根据截取字符串 = 和 截取长度 7
                                //027272=027272=027272=027272=027272=027272=027272=027272=
                                // 处理字符串 根据截取字符串 = 和 截取长度 7
                                String[] dataArray = receivedData.split(weightConfig.getSubstr());
                                for (int j = 0; j < dataArray.length; j++) {
//                                    System.out.println("Data[" + j + "]: " + dataArray[j]);
                                    // 如果需要限制长度为7
//                                    if (dataArray[j].length() > 7) {
//                                        dataArray[j] = dataArray[j].substring(0, 7);
//                                    }
                                    // 经过存储过程处理 保存数据库
                                    carsMapper.insertWeight(dataArray[j]);
                                }

                            }
                        } else {
                            System.out.println("No data available on serial port.");
                            return "0.000"; // 没有数据时返回默认值
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace(); // 打印异常信息
                    return "ERROR: " + e.getMessage(); // 发生异常时返回错误信息
                } finally {
                    comPort.closePort(); // 关闭串口，无论是否发生异常都应关闭串口以释放资源
                    System.out.println("Port closed.");
                }
            } else {
                System.out.println("No serial ports found."); // 如果没有找到串口，打印提示信息
            }
            //获取值 根据存储过程 处理最后三次数据一致则取值
            carsMapper.updateWeight();
            BigDecimal weightResult = carsMapper.selectWeight();
            return String.valueOf(weightResult);
        }

        return "0.000"; // 默认返回值
    }

}
